<template>
  <div>
    <!-- 搜索框 -->
    <van-search
      v-model.trim="keywords"
      background="#3692fa"
      show-action
      placeholder="请输入搜索关键词"
      class="search"
      @search="onSearch"
      @focus="onSearchFocus"
      @cancel="$router.back()"
    />
    <!-- 搜索历史/建议/结果 -->
    <!-- <search-suggestion></search-suggestion> -->
    <!-- <search-result></search-result> -->
    <!-- <search-history></search-history> -->
    <component
      :is="componentName"
      :keywords="keywords"
      :historyArr="historyArr"
      @updateHistoryArr="updateHistoryArr"
      @getKeywordsFromHistory="getKeywordsFromHistory"
    ></component>
  </div>
</template>

<script>
import { getHistory, setHistory } from '@/utils/auth'
import SearchHistory from './components/SearchHistory.vue'
import SearchResult from './components/SearchResult.vue'
import SearchSuggestion from './components/SearchSuggestion.vue'
export default {
  name: 'Search',
  components: {
    SearchHistory,
    SearchResult,
    SearchSuggestion
  },
  data() {
    return {
      keywords: '',
      historyArr: getHistory() || [],
      //? 用于记录用户是否搜索了
      isShowSearchResults: false
    }
  },
  computed: {
    componentName() {
      //? 如果输入的是空字符串那么渲染搜索历史
      if (this.keywords === '') {
        return 'SearchHistory'
      }

      if (this.isShowSearchResults) {
        //? 用变量记录是否显示搜索结果
        return 'SearchResult'
      }

      //? 既不显示历史 也不显示结果，渲染建议
      return 'SearchSuggestion'
    }
  },
  methods: {
    getKeywordsFromHistory(keywords) {
      this.keywords = keywords
      this.onSearch()
    },
    updateHistoryArr() {
      this.historyArr = getHistory() || []
    },
    onSearch() {
      this.isShowSearchResults = true

      if (this.historyArr.indexOf(this.keywords) === -1) {
        this.historyArr.unshift(this.keywords)
        setHistory(this.historyArr)
      } else {
        this.historyArr.splice(this.historyArr.indexOf(this.keywords), 1)
        this.historyArr.unshift(this.keywords)
        setHistory(this.historyArr)
      }
    },
    onSearchFocus() {
      //? 如果keywords为'', 显示搜索历史
      //? 如果keywords有值, 显示搜索建议
      this.isShowSearchResults = false
    }
  }
}
</script>

<style lang="less" scoped>
.search {
  //! 搜索框样式  属性设置
  [role='button'] {
    color: #fff;
  }
}
</style>
